import filterData from '@/common/filterData';
import mergeData from '@/common/mergeData';
import formatter from '@/common/formatter';
import getDepartment from '@/common/getDepartment';
const { departOrder } = getDepartment;

const base = { title: '开通在途情况' }
const dataset = {
  source: [
    ['日期', '在途', '超长', '预警'],
    ['茂南', 186, 100, 179, 43]
  ]
};
const seriesTemplate = [['bar', 'bar', 'bar']];
/**
 * 
 * @param {{[collection]:{[biz]:Array<{date:number,region:string,grid:string,count:number}>}}} dataPool 
 * @param {[string[],string[]]} condition 
 * @returns {Array}
 */
function getChartData([dataPool1], condition) {
  const defaultCondition = ['茂南', '电白', '高州', '化州', '信宜'];

  const hasCondition = condition && condition.length && (condition[0].length || condition[1].length);

  const regionCondition = hasCondition ? [...condition[0]] : defaultCondition;
  const gridCondition = hasCondition ? [...condition[1]] : [];

  const biz = ['all', 'chaochang', 'yujing'];
  const sheetHeaderMain = ['在途'];
  const sheetHeaderStack = ['超长', '预警'];
  const SheetHeader = [...sheetHeaderMain, ...sheetHeaderStack];
  const collection = dataPool1['kuandai_zt'];

  const sheets = biz.map((biz, bizIndex) => {
    let data = collection[biz];
    const latestDate = Math.max(...data.map(i => i.date));
    data = data.filter(i => i.date === latestDate);

    let regionData = [], gridData = [];
    if (regionCondition.length) {
      regionData = filterData.countByField('region', data, regionCondition, true);
    }
    if (gridCondition.length) {
      gridData = filterData.countByField('grid', data, gridCondition, true);
    }
    const rgdata = regionData.concat(gridData).sort((a, b) => departOrder[a[0]] - departOrder[b[0]])
    const merge = [
      ['地区', SheetHeader[bizIndex]]
    ].concat(rgdata);
    return merge;
  });

  const data = mergeData.mergeSheets(sheets).map(row => row.map(item => item || 0));
  this.dataset.source = data;

  const series = [];

  seriesTemplate.forEach((items, itemsIndex) => {
    items.forEach((type, typeIndex) => {
      series.push({
        type,
        yAxisIndex: itemsIndex,
        stack: sheetHeaderStack.includes(SheetHeader[typeIndex]) ? 'focused' : false,
        label: {
          show: sheetHeaderMain.includes(SheetHeader[typeIndex]) || SheetHeader[typeIndex] === sheetHeaderStack[sheetHeaderStack.length - 1],
          position: 'top',
          formatter: (params) => {
            if (SheetHeader[typeIndex] === sheetHeaderStack[sheetHeaderStack.length - 1]) {
              const { dimensionNames, data } = params;
              const mainValue = sheetHeaderMain.map(item => data[dimensionNames.indexOf(item)]).reduce((acc, cur) => !isNaN(Number(cur)) ? acc + Number(cur) : acc, 0),
                stackValue = sheetHeaderStack.map(item => data[dimensionNames.indexOf(item)]).reduce((acc, cur) => !isNaN(Number(cur)) ? acc + Number(cur) : acc, 0),
                proportion = stackValue / mainValue;
              return `${formatter.valueToText(stackValue)}（${formatter.valueToText(proportion, true)}）`
            }
          }
        }
      })
    });
  });

  this.series = series;

  // 非日期类
  // if (data.length > 7) {
  //   this.dataZoom[0].show = true;
  //   this.dataZoom[0].type = 'inside'
  // }

  // 返回数据到页面缓存
  return data

}

// ======更新内容↑========

export default {
  title: {
    text: base.title,
    left: 'center'
  },
  legend: {
    type: 'scroll',
    top: 30,
    selected: {
      '在途': false
    }
  },
  color: ['#5470c6', 'red', 'yellow', 'orange'],
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  grid: {
    width: '96%',
    height: '78%',
    left: '2%',
    right: '2%',
    top: '20%',
    bottom: '2%',
    containLabel: true
  },
  dataset,
  dataZoom: [{ show: false }],
  xAxis: {
    type: 'category',
    axisPointer: {
      type: 'shadow'
    }
  },
  yAxis: [
    {
      type: 'value',
      name: ''

    }, {
      type: 'value',
      name: '',
      axisLabel: {
        formatter: (value) => `${value}`
      }
    }
  ],
  series: [{ type: 'bar' }],
  getChartData,
}